package com.tieto.springboot.demo.customsession;

import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;

import redis.clients.jedis.Jedis;

public class CustomSession implements HttpSession {

	private String mJessionId = null;
	private int activeTnterval = 1800;
	private ServletContext mServletContext = null;

	public CustomSession(String pId,ServletContext pServletContext) {
		this.mJessionId = pId;
		this.mServletContext = pServletContext;
	}

	public Object getAttribute(String attributeName, Class<?> clazz) {
		Jedis jedis = JedisPoolUtil.getJedis();
		String jsonStr = jedis.hget(mJessionId, attributeName);
		jedis.close();
		return JedisPoolUtil.convertTo(jsonStr, clazz);
	}

	@Override
	public Object getAttribute(String attributeName) {
		Jedis jedis = JedisPoolUtil.getJedis();
		String fieldValue = jedis.hget(mJessionId, attributeName);
		Object attributeValue = JedisPoolUtil.conver2MapOrString(fieldValue);
		jedis.close();
		return attributeValue;
	}

	@Override
	public Enumeration<String> getAttributeNames() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getCreationTime() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getId() {
		return mJessionId;
	}

	@Override
	public long getLastAccessedTime() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int getMaxInactiveInterval() {
		return activeTnterval;
	}

	@Override
	public ServletContext getServletContext() {
		return mServletContext;
	}

	@Override
	public HttpSessionContext getSessionContext() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object getValue(String arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String[] getValueNames() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void invalidate() {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean isNew() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void putValue(String arg0, Object arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void removeAttribute(String key) {
		Jedis jedis = JedisPoolUtil.getJedis();
		jedis.hdel(mJessionId, key);
		jedis.close();
	}

	@Override
	public void removeValue(String arg0) {

	}

	@Override
	public void setAttribute(String key, Object obj) {
		Jedis jedis = JedisPoolUtil.getJedis();
		String jsonObj = JedisPoolUtil.toJson(obj);
		jedis.hset(mJessionId, key, jsonObj);
		jedis.expire(mJessionId, activeTnterval);
		jedis.close();

	}

	@Override
	public void setMaxInactiveInterval(int millisecond) {
		this.activeTnterval = millisecond / 1000;
	}
	
	
}
